/**
 * 功能： LED智能灯控制系统 设备端2
 * 作者： 单片机菜鸟哥
 * 时间： 2020-02-28
 * 通信方式：MQTT客户端直连
 *
 * 详细描述：
 *   1、esp8266连接上wifi热点
 *   2、通过mqtt client方式连接上阿里云物联网平台
 *   3、MQTT fx客户端发送控制LED指令到设备端，达到控制亮灭的作用
 *
 */

#include <ESP8266WiFi.h>
#include <ArduinoJson.h>
#include <PubSubClient.h>
#include <WiFiClientSecure.h>

const char* WIFI_SSID     = "TP-LINK_5344"; // WiFi账号密码
const char* WIFI_PASSWORD = "6206908you11011010"; // WiFi密码

/******************产品/设备配置(每个人需要根据自己的产品设备信息去动态更换)**********************/
#define PRODUCT_KEY "a1yPA4CufD2"  //产品key  从产品详情获取
#define DEVICE_NAME "LED_Device2"  //设备deviceName  从设备详情获取
// 服务端相关
#define MQTT_SERVER   PRODUCT_KEY ".iot-as-mqtt.cn-shanghai.aliyuncs.com" //阿里云MQTT服务地址
#define MQTT_PORT     1883                                               //MQTT服务端口
// 校验三元组
#define MQTT_CLIENT_ID  DEVICE_NAME "|securemode=3,signmethod=hmacsha1|" //mqtt clientid
#define MQTT_USERNAME   DEVICE_NAME "&" PRODUCT_KEY                      //mqtt username
#define MQTT_PASSWORD   "B6E44FE36CA7F775FAD80EAAB983D2B8900AC103"       //mqtt password 通过生成工具获得
// 相关主题 自定义一个主题
#define TOPIC1 "/" PRODUCT_KEY "/" DEVICE_NAME "/user/setledstatus"
/*************************************************************************************************/

void mqtt_callback (char* topic, byte* payload, unsigned int length);
void doWiFiTick();
void connect_wifi();
void connectToMqtt();
const __FlashStringHelper* connectErrorToString(int8_t code);

BearSSL::WiFiClientSecure client_s;
PubSubClient mqttclient(MQTT_SERVER, MQTT_PORT, &mqtt_callback, client_s);

void setup() {
  // put your setup code here, to run once:
  delay(2000);
  Serial.begin(115200);
//  Serial.print("MQTT_SERVER:");
//  Serial.println(MQTT_SERVER);
//  Serial.print("MQTT_CLIENT_ID:");
//  Serial.println(MQTT_CLIENT_ID);
//  Serial.print("MQTT_USERNAME:");
//  Serial.println(MQTT_USERNAME);
//  Serial.print("TOPIC1:");
//  Serial.println(TOPIC1);
  pinMode(LED_BUILTIN, OUTPUT);
  client_s.setInsecure();
  Serial.println("");
}

void loop() {
  // put your main code here, to run repeatedly:
  ESP.wdtFeed();
  doWiFiTick();
  if (WiFi.status() == WL_CONNECTED) {
    connectToMqtt();
    mqttclient.loop();
  }
  delay(2000);
}

/**
 * 功能：连接到Mqtt
 */
void connectToMqtt() {
  if (mqttclient.connected()) {
   return;
  }

  Serial.print(F("Connecting to MQTT... "));

  int8_t ret;
  uint8_t retries = 3;

  while (!mqttclient.connect(MQTT_CLIENT_ID, MQTT_USERNAME,MQTT_PASSWORD)) { // connect will return true for connected
      Serial.println(connectErrorToString(mqttclient.state()));
      Serial.println(F("Retrying MQTT connection in 5 seconds..."));
      mqttclient.disconnect();
      delay(5000);  // wait 5 seconds
      retries--;
      if (retries == 0) {
        // basically die and wait for WDT to reset me
        while (1);
      }
      yield();
  }
  Serial.println(F("Success!"));
  // 订阅主题
  mqttclient.subscribe(TOPIC1);

}

/**
 * 功能：连接路由心跳函数
 */
void doWiFiTick() {
  static bool taskStarted = false;
  static bool startSTAFlag = false;
  static uint32_t lastWiFiCheckTick = 0;

  if (!startSTAFlag) {
    startSTAFlag = true;

    Serial.print("connect to ap:");
    Serial.println(WIFI_SSID);
    WiFi.disconnect();
    WiFi.mode(WIFI_STA);
    WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
    Serial.printf("Heap size:%d\r\n", ESP.getFreeHeap());
  }

  //未连接1s重连
  if ( WiFi.status() != WL_CONNECTED ) {
    if (millis() - lastWiFiCheckTick > 1000) {
      lastWiFiCheckTick = millis();
      Serial.print(".");
    }
  }
  //连接成功建立
  else {
    if (taskStarted == false) {
      taskStarted = true;
      Serial.print("\r\nGet IP Address: ");
      Serial.println(WiFi.localIP());
    }
  }
}

/**
 * 功能：MQTT回调
 * 参数：
 *   1. topic   主题
 *   2. payload 载体
 *   3. length  载体长度
 */
void mqtt_callback (char* topic, byte* payload, unsigned int length) {
  byte *end = payload + length;
  for (byte *p = payload; p < end; ++p) {
    Serial.print(*((const char *)p));
  }
  Serial.println("");
  parseMqttResponse((char *)payload);
}

/**
 * 解析mqtt数据
 */
void parseMqttResponse(char* payload){
   Serial.println("start parseOneNetMqttResponse");
   StaticJsonBuffer<100> jsonBuffer;
     // StaticJsonBuffer 在栈区分配内存   它也可以被 DynamicJsonBuffer（内存在堆区分配） 代替
     // DynamicJsonBuffer  jsonBuffer;
   JsonObject& root = jsonBuffer.parseObject(payload);

     // Test if parsing succeeds.
   if (!root.success()) {
       Serial.println("parseObject() failed");
       return ;
   }

   String deviceName = root["dn"];
   int status = root["s"];

   if(strcmp(DEVICE_NAME,deviceName.c_str())== 0){
        if (status == 1) {
            digitalWrite(LED_BUILTIN, LOW);
        } else {
            digitalWrite(LED_BUILTIN, HIGH);
        }
    }
}

/**
 * 功能：打印错误
 * 参数：
 *   1. code   错误码
 */
const __FlashStringHelper* connectErrorToString(int8_t code) {
   switch (code) {
      case 1: return F("The Server does not support the level of the MQTT protocol requested");
      case 2: return F("The Client identifier is correct UTF-8 but not allowed by the Server");
      case 3: return F("The MQTT service is unavailable");
      case 4: return F("The data in the user name or password is malformed");
      case 5: return F("Not authorized to connect");
      case 6: return F("Exceeded reconnect rate limit. Please try again later.");
      case 7: return F("You have been banned from connecting. Please contact the MQTT server administrator for more details.");
      case -1: return F("Connection failed");
      case -2: return F("Failed to subscribe");
      case -3: return F("Connection Lost");
      case -4: return F("Connection Timeout");
      default: return F("Unknown error");
   }
}
